package com.heima.kafka.simple;

import org.apache.kafka.clients.consumer.*;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消费者，应该是一直处于监听状态
 */
public class ConsumerQuickStart {
    public static void main(String[] args) {

        //2.添加配置信息
        Properties properties=new Properties();
        //连接kafka信息
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.229.142:9092");
        //对key进行字符串反序列操作
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        //对value也要进行字符串反序列操作
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringDeserializer");
        //添加groupId,消费者
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group2");
        //添加设置手动提交偏移量
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG,false);
        //1.创建消费者对象
        KafkaConsumer<String,String> kafkaConsumer=new KafkaConsumer<String, String>(properties);
        //3.订阅主题，表示监听哪个队列
        kafkaConsumer.subscribe(Collections.singletonList("kafkastream-toipc2"));

        //4.拉取消息内容
        while (true){
            ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(10));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println("消息的key:"+record.key()+",消息的value:"+record.value());
                //表示同步提交偏移量
                //kafkaConsumer.commitSync();
                //异步提交
               /* kafkaConsumer.commitAsync(new OffsetCommitCallback() {
                    @Override
                    public void onComplete(Map<TopicPartition, OffsetAndMetadata> offsets, Exception exception) {
                        if(exception!=null){
                            System.out.println("异常信息："+exception);
                            //重试提交操作
                        }
                    }
                });*/
            }
        }
    }
}
